<?php

namespace App\Models\Goods;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class Goods extends Model
{
    //使用软删除
    use SoftDeletes;
    //关联表
    protected $table = 'goods';
    //填充字段
    protected $guarded = ['description','content'];
    //设置主键
    protected $primaryKey = 'id';
    //软删除自动维护字段,不为空时此条数据不显示
    protected $dates = ['deleted_at'];
    /**
     * validate 表单数据验证
     *
     * @param $data
     * @return bool
     */
    public  static function validate($data){
        return $v =Validator::make($data, [
            'name'=>[
                'required',
                Rule::unique('goods')->where(function ($query) use($data) {
                    if(array_key_exists('id', $data)){
                        $query->where('id', '!=', $data['id']);
                    }
                })
            ],
            'cate_id'=>'required|integer',
//            'thumb'=>'required',
            'picture'=>'sometimes|required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
/*            'picture'=>'required',*/
            'price'=>'required|numeric|min:0',
            'stock'=>'required|numeric|min:0',
            'on_sale'=>'required|integer',
            'is_recommented'=>'required|integer',
        ],[
                'name.required' => '名称不能为空！',
                'name.unique' => '商品名称已经存在！',
                'cate_id.required' => '请选择商品父级分类！',
/*                'thumb.required' => '请上传一张图片！',*/
                'picture.required' => '请上传一张图片！',
                'picture.image' => '您上传的不是图片类型！',
                'picture.mimes' => '图片格式：jpeg,png,jpg,gif,svg！',
                'picture.max' => '允许上传的最大图片值：2MB！',
                'price.required' => '请设置商品的价格！',
                'price.numeric' => '请正确设置商品价格！',
                'price.min' => '价格需大于0！',
                'stock.required' => '请设置商品库存！',
                'stock.numeric' => '请正确设置商品库存！',
                'stock.min' => '库存需大于0！',
                'on_sale.required' => '请选择商品是否上架！',
                'is_recommented.required' => '请选择商品是否作为推荐产品！',
            ]
        );
    }

    /**
     * getList 获取商品列表
     * 
     * @param bool $isSoftDel
     * @return mixed
     */
    public static function getList($isSoftDel = true){
        $db = $isSoftDel ? Goods::withoutTrashed() : Goods::onlyTrashed();
        return $db
            ->join('goods_cate', 'goods.cate_id', '=', 'goods_cate.id')
            ->select('goods.*','goods_cate.*','goods_cate.name as cate_name','goods.description as despt','goods.name as goods_name','goods.id as gid')
            ->orderBy('goods.created_at','asc')
            ->paginate(10);
    }
}
